package cn.happyjava.springbootsecurity.config;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @Author: zlxiao
 * @Date: 2019/9/8 14:08
 */
@Component
public class ApiTokenFilter extends GenericFilterBean {

    @Autowired
    private ApiKeyAuthenticationManager apiKeyAuthenticationManager;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            String apiKey = request.getHeader("tfapi-key");
            if (StringUtils.isBlank(apiKey)) {
                apiKey = request.getParameter("appKey");
            }

            if (StringUtils.isNotBlank(apiKey)) {
                try {
                    Authentication authResult = apiKeyAuthenticationManager.authenticate(new UsernamePasswordAuthenticationToken(null, apiKey));
                    if (authResult != null && authResult.isAuthenticated()) {
                        logger.info("Authentication success with api key : " + apiKey);
                        SecurityContextHolder.getContext().setAuthentication(authResult);
                    }
                } catch (AuthenticationException var8) {
                    SecurityContextHolder.clearContext();
                }
            }
        }

        filterChain.doFilter(servletRequest, servletResponse);
    }

}
